#pragma once

#include <iostream>
#include <fstream>
#include <mutex>
#include <vector>
#include <algorithm>
#include <cassert>
#include <json/json.h>
// #include "oj_model.hpp"
#include "oj_model2.hpp"
#include "oj_view.hpp"
#include "../comm/log.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"

namespace ns_control
{
    using namespace std;
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_util;
    using namespace httplib;

    // 提供服务的主机
    class Machine
    {
    public:
        string ip;       // 编译服务的ip
        int port;        // 编译服务的端口
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // mutex禁止拷贝，使用指针
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}
        // 增加主机负载
        void IncLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 减少主机负载
        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        // 重置负载
        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }
        // 获取主机负载(只是为了统一接口)
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }
    };

    const string service_machine = "./conf/service_machine.conf";

    // 负载均衡模块
    class LoadBalance
    {
    private:
        // 可以提供编译的所有主机
        std::vector<Machine> machines;
        // 所有在线的主机id,即索引
        std::vector<int> online;
        // 所有离线的主机id
        std::vector<int> offline;
        // 保证LoadBalance的数据安全
        std::mutex mtx;

    public:
        LoadBalance()
        {
            assert(LoadConf(service_machine));
            LOG(INFO) << "加载 " << service_machine << " 成功" << std::endl;
        }
        ~LoadBalance() {}
        // 加载 conf 配置，填充 machines
        bool LoadConf(const string &machine_conf)
        {
            std::ifstream in(machine_conf);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载: " << machine_conf << " 失败" << std::endl;
                return false;
            }
            string line;
            while (std::getline(in, line))
            {
                std::vector<string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << " 切分 " << line << " 失败 " << std::endl;
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();

                online.push_back(machines.size()); // 插入新主机的索引
                machines.push_back(m);
            }
            in.close();
            return true;
        }
        // 选择负载最小或空闲的机器
        bool SmartChoice(int *id, Machine **m)
        {
            // 使用负载最低的主机
            mtx.lock();
            // 负载均衡的算法 1.随机数+hash 2.轮询+hash
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << "所有后端编译主机已离线" << std::endl;
                return false;
            }
            // 通过遍历的方式，找到负载最小的机器
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 1; i < online_num; ++i)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        // 标记某台机器离线
        void OfflineMachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    // 找到要离线的主机
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }
        // 标记某台机器上线
        void OnlineMachine()
        {
            // 统一上线
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();
            LOG(INFO) << "所有主机已经上线" << std::endl;
        }
        void ShowMachines()
        {
            mtx.lock();
            std::cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                cout << id << ' ';
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                cout << id << ' ';
            }
            std::cout << std::endl;
            mtx.unlock();
        }
    };

    // 核心业务逻辑的控制器
    class Control
    {
    private:
        Model _model;              // 提供后台数据
        View _view;                // 提供html渲染功能
        LoadBalance _load_balance; // 核心负载均衡器

    public:
        void RecoveryMachines()
        {
            _load_balance.OnlineMachine();
        }
        // 根据题目数据构建网页
        bool AllQuestions(string *html)
        {
            bool ret = true;
            vector<struct Question> all;
            if (_model.GetAllQuestions(&all))
            {
                std::sort(all.begin(), all.end(), [](const struct Question &q1, const struct Question &q2)
                          { return std::stoi(q1.number) < std::stoi(q2.number); });
                // 获取题目数据成功，将所有的题目构建成网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                ret = false;
            }
            return ret;
        }
        // 获取指定题目的网页
        bool Question(const string &number, string *html)
        {
            bool ret = true;
            struct Question q;
            if (_model.GetOneQuestion(number, &q))
            {
                // 获取指定题目信息成功，构建成网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题目" + number + "不存在!";
                ret = false;
            }
            return ret;
        }

        void Judge(const string &number, const string &in_json, string *out_json)
        {
            // LOG(DEBUG) << in_json << " \nnumber: " << number << std::endl;
            // 1.根据题目编号，直接拿到对应题目细节
            struct Question q;
            _model.GetOneQuestion(number, &q);

            // 2. in_json进行反序列化, 得到题目的id, 得到用户的源代码, input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();

            // 3. 重新拼接用户代码+测试用例代码, 形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            string compile_string = writer.write(compile_value);

            // 4. 选择负载最低的主机
            // 一直选择直到主机可用, 否则全部挂掉
            while (1)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_balance.SmartChoice(&id, &m))
                {
                    break;
                }

                // 5. 发起http请求, 得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                LOG(INFO) << "选择主机成功, 主机id: " << id << " 详情: "
                          << m->ip << ":" << m->port << " 当前主机的负载是：" << m->Load() << std::endl;
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 6. 将结果赋值给out_json
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFO) << "请求编译和运行服务器成功..." << std::endl;
                        break;
                    }
                    else
                    {
                        LOG(ERROR) << "响应失败，状态码：" << res->status << ", 主机: " << m->ip << ":" << m->port << std::endl;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << " 当前请求的主机id: " << id << " 详情: " << m->ip << ":" << m->port << "可能已经离线" << std::endl;
                    _load_balance.OfflineMachine(id); // 把主机从在线列表中移除
                    _load_balance.ShowMachines();     // for debug
                }
            }
        }
    };
}
